package com.squirrels.server.config;

import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.squirrels.server.work.ServerWorker;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.config.MorphiaConfig;
import jakarta.annotation.PostConstruct;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.security.Security;
import java.util.concurrent.ConcurrentHashMap;

import static com.mongodb.MongoClientSettings.builder;
import static org.bson.UuidRepresentation.STANDARD;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/7/31 11:19
 * 描述: MongoDB数据库配置
 */
@Configuration
public class MongoConfig {

    @Value("${database.mongoDB.url}")
    private String url;

    private MongoClient mongoClient;

    private Datastore datastore;

    @PostConstruct
    public void buildMongo() throws IOException {
        createMongoClient();
        createMongoDatastore();
    }

    public void createMongoClient() {
        mongoClient = MongoClients.create(builder()
                .uuidRepresentation(STANDARD)
                .applyConnectionString(new ConnectionString(url))
                .build());
    }

    public void createMongoDatastore() {
        // 注册 Bouncy Castle 加密提供者
        Security.addProvider(new BouncyCastleProvider());
        // 注册 Bouncy Castle JSSE 提供者
        Security.addProvider(new BouncyCastleJsseProvider());
        MorphiaConfig morphiaConfig = MorphiaConfig.load("morphia-config.properties");
        datastore = Morphia.createDatastore(mongoClient,morphiaConfig);
    }

    // 将datastore注入worker
    public void injectDatastore(ConcurrentHashMap<String, ServerWorker> workers){
        for (ServerWorker worker : workers.values()) {
            worker.setDatastore(datastore);
        }
    }

    // 关闭连接
    public void stop() {
        mongoClient.close();
    }
}
